package com.cqhfan.chatroom.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.cqhfan.chatroom.domain.dto.WebSocketMessageDTO;
import com.cqhfan.chatroom.domain.po.ChatMessage;
import com.cqhfan.chatroom.enums.ChatType;
import com.cqhfan.chatroom.enums.MessageType;
import com.cqhfan.chatroom.handler.UserConnectionSession;
import com.cqhfan.chatroom.mapper.ChatMessageMapper;
import com.cqhfan.chatroom.service.IChatGroupUserService;
import com.cqhfan.chatroom.service.IChatMessageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqhfan.common.exceptions.BizException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.time.LocalDateTime;

/**
 * <p>
 * 聊天消息记录 服务实现类
 * </p>
 *
 * @author 眭传洪
 * @since 2024-11-20
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ChatMessageServiceImpl extends ServiceImpl<ChatMessageMapper, ChatMessage> implements IChatMessageService {

    private final IChatGroupUserService chatGroupUserService;

    @Override
    public void saveChatMessage(String msg) {
        WebSocketMessageDTO dto = JSONUtil.toBean(msg, WebSocketMessageDTO.class);
        ChatMessage chatMessage = new ChatMessage();
        BeanUtil.copyProperties(dto, chatMessage, "chatType", "messageType");
        chatMessage.setMessageType(MessageType.fromValue(dto.getMessageType()));
        chatMessage.setChatType(ChatType.fromValue(dto.getChatType()));
        chatMessage.setCreateTime(LocalDateTime.now());
        save(chatMessage);
    }

    @Override
    public void listenSendMsg(String msg) {
        // 解析消息
        WebSocketMessageDTO chatMessage = JSONUtil.toBean(msg, WebSocketMessageDTO.class);
        // 根据不同情况发消息
        ChatType chatType = ChatType.fromValue(chatMessage.getChatType());
        if (ChatType.SINGLE == chatType) {
            Long receiverId = chatMessage.getReceiverId();
            WebSocketSession receiveSession = UserConnectionSession.getSessionByUserId(receiverId);
            if (receiveSession != null && receiveSession.isOpen()) {
                try {
                    receiveSession.sendMessage(new TextMessage(msg));
                } catch (IOException e) {
                    throw new BizException(e.getMessage());
                }
            }
        } else {
            // 群聊消息发送
            chatGroupUserService.noticeChatGroupCreateMsg(msg);
        }
    }
}
